// @flow
import React, { Component } from 'react'
import styles from './AMQSetting.css'
import { Button } from 'antd'
import AMQSettingGrid from './AMQSettingGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {
  history: Object
}
type States = {
  menus: Array<Object>,
  total: number,
  current: number,
  pageSize: number
}
class AMQSetting extends Component {
  props: Props
  state: States
  getAMQSettings: Function
  addAMQSetting: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      menus: [],
      total: 0,
      current: 1,
      pageSize: 20
    }
    this.getAMQSettings = this.getAMQSettings.bind(this)
    this.addAMQSetting = this.addAMQSetting.bind(this)
  }

  componentDidMount () {
    this.getAMQSettings(this.state.current, this.state.pageSize)
  }

  getAMQSettings (page: number, pageSize: number) {
    universalFetch(`${__SERVICE_API__}sys/amq?pageNum=${page}&pageSize=${pageSize}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo ? json.pageInfo.total : 1,
          menus: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  addAMQSetting () {
    this.props.history.push('/system/amq-add')
  }
  render () {
    const { menus, current, pageSize, total } = this.state
    return (
      <div className={styles['main']}>
        <div className={styles['action']}>
          <Button onClick={this.addAMQSetting}>添加配置</Button>
        </div>
        <AMQSettingGrid {...{
          current,
          pageSize,
          total,
          refreshAMQSettings: this.getAMQSettings,
          rowData: menus,
          history: this.props.history
        }} />
      </div>
    )
  }
}

export default AMQSetting
